from fastapi import APIRouter, HTTPException, UploadFile, File
from fastapi.responses import FileResponse
from pydantic import BaseModel, Field
from typing import List, Optional
import os
import mimetypes
from ..routes import mdmanage

router = APIRouter()

# 数据模型
class DocumentInfo(BaseModel):
    """文档信息模型"""
    id: int
    name: str
    type: str
    size: int
    path: str
    created_at: Optional[str] = None

class ZipInfo(BaseModel):
    """ZIP文件信息模型"""
    id: int
    zip_name: str
    extract_path: str
    md_files: List[str]
    file_count: int
    status: str

class DocumentResponse(BaseModel):
    """文档响应模型"""
    status: str
    message: str
    data: Optional[dict] = None

@router.get("/documents", response_model=DocumentResponse)
async def get_document_list():
    """获取文档列表"""
    try:
        zip_objects = mdmanage.get_zip_objects()
        return DocumentResponse(
            status="success",
            message=f"找到 {len(zip_objects)} 个文档项目",
            data={
                "documents": zip_objects,
                "total": len(zip_objects)
            }
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取文档列表失败: {str(e)}")

@router.get("/documents/{doc_id}", response_model=DocumentResponse)
async def get_document_detail(doc_id: int):
    """获取文档详情"""
    try:
        zip_object = mdmanage.get_zip_object_by_id(doc_id)
        if not zip_object:
            raise HTTPException(status_code=404, detail="文档不存在")
        
        # 获取文档中的所有文件
        all_files = mdmanage.get_all_files(zip_object['extract_path'])
        
        return DocumentResponse(
            status="success",
            message="获取文档详情成功",
            data={
                "document": zip_object,
                "files": all_files
            }
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取文档详情失败: {str(e)}")

@router.get("/documents/{doc_id}/files/{file_name}")
async def get_file_content(doc_id: int, file_name: str):
    """获取文档文件内容"""
    try:
        zip_object = mdmanage.get_zip_object_by_id(doc_id)
        if not zip_object:
            raise HTTPException(status_code=404, detail="文档不存在")
        
        file_path = os.path.join(zip_object['extract_path'], file_name)
        if not os.path.exists(file_path):
            raise HTTPException(status_code=404, detail="文件不存在")
        
        # 检查文件类型
        file_extension = file_name.split('.')[-1].lower() if '.' in file_name else ''
        
        # 如果是图片文件，返回JSON格式的base64数据
        if file_extension in ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg']:
            import base64
            with open(file_path, 'rb') as f:
                image_data = base64.b64encode(f.read()).decode()
            
            # 获取MIME类型
            mime_type = mimetypes.guess_type(file_path)[0] or 'application/octet-stream'
            
            return DocumentResponse(
                status="success",
                message="获取图片文件成功",
                data={
                    "file_name": file_name,
                    "file_type": "image",
                    "file_extension": file_extension,
                    "mime_type": mime_type,
                    "image_data": f"data:{mime_type};base64,{image_data}",
                    "is_image": True
                }
            )
        
        # 读取文件内容（非图片文件）
        elif file_name.endswith('.md'):
            try:
                content = mdmanage.read_md_file_content(file_path)
                return DocumentResponse(
                    status="success",
                    message="获取文件内容成功",
                    data={
                        "file_name": file_name,
                        "file_type": "markdown",
                        "content": content,
                        "is_image": False
                    }
                )
            except UnicodeDecodeError:
                # 尝试使用其他编码
                try:
                    with open(file_path, 'r', encoding='gbk') as file:
                        content = file.read()
                    return DocumentResponse(
                        status="success",
                        message="获取文件内容成功",
                        data={
                            "file_name": file_name,
                            "file_type": "markdown",
                            "content": content,
                            "is_image": False
                        }
                    )
                except Exception as e:
                    raise HTTPException(status_code=500, detail=f"读取Markdown文件失败: {str(e)}")
            except Exception as e:
                raise HTTPException(status_code=500, detail=f"读取Markdown文件失败: {str(e)}")
        else:
            # 对于非MD文件，返回基本信息
            file_size = os.path.getsize(file_path)
            return DocumentResponse(
                status="success", 
                message="获取文件信息成功",
                data={
                    "file_name": file_name,
                    "file_type": file_name.split('.')[-1] if '.' in file_name else 'unknown',
                    "file_size": file_size,
                    "message": "非文本文件，无法显示内容",
                    "is_image": False
                }
            )
    
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取文件内容失败: {str(e)}")

@router.get("/documents/image/{file_name}")
async def get_image_file_simple(file_name: str):
    """直接通过文件名返回图片文件（递归查找所有文档）"""
    try:
        # 获取所有ZIP对象，递归查找包含该文件的文档
        all_zips = mdmanage.get_zip_objects()
        
        for zip_obj in all_zips:
            # 递归查找文件
            for root, dirs, files in os.walk(zip_obj['extract_path']):
                if file_name in files:
                    file_path = os.path.join(root, file_name)
                    
                    # 检查是否为图片文件
                    file_extension = file_name.split('.')[-1].lower() if '.' in file_name else ''
                    if file_extension not in ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg']:
                        raise HTTPException(status_code=400, detail="不是图片文件")
                    
                    # 获取MIME类型
                    mime_type = mimetypes.guess_type(file_path)[0] or 'application/octet-stream'
                    
                    return FileResponse(
                        path=file_path,
                        media_type=mime_type,
                        filename=file_name
                    )
        
        raise HTTPException(status_code=404, detail="图片文件不存在")
    
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取图片文件失败: {str(e)}")

@router.get("/documents/{doc_id}/image/{file_name}")
async def get_image_file(doc_id: int, file_name: str):
    """直接返回图片文件（用于在浏览器中直接显示）"""
    try:
        zip_object = mdmanage.get_zip_object_by_id(doc_id)
        if not zip_object:
            raise HTTPException(status_code=404, detail="文档不存在")
        
        file_path = os.path.join(zip_object['extract_path'], file_name)
        if not os.path.exists(file_path):
            raise HTTPException(status_code=404, detail="文件不存在")
        
        # 检查是否为图片文件
        file_extension = file_name.split('.')[-1].lower() if '.' in file_name else ''
        if file_extension not in ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg']:
            raise HTTPException(status_code=400, detail="不是图片文件")
        
        # 获取MIME类型
        mime_type = mimetypes.guess_type(file_path)[0] or 'application/octet-stream'
        
        return FileResponse(
            path=file_path,
            media_type=mime_type,
            filename=file_name
        )
    
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取图片文件失败: {str(e)}")

@router.get("/documents/zip/status")
async def get_zip_status():
    """获取ZIP文件处理状态"""
    try:
        # 检查zip目录是否有文件
        zip_files = mdmanage.has_zip_files('zip')
        
        return DocumentResponse(
            status="success",
            message="获取ZIP状态成功",
            data={
                "has_zip_files": bool(zip_files),
                "zip_files": zip_files if zip_files else [],
                "zip_count": len(zip_files) if zip_files else 0
            }
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取ZIP状态失败: {str(e)}")

@router.post("/documents/upload")
async def upload_document(file: UploadFile = File(...)):
    """上传文档文件"""
    try:
        # 检查文件类型
        if not file.filename.endswith('.zip'):
            raise HTTPException(status_code=400, detail="只支持ZIP文件上传")
        
        # 确保目录存在
        zip_dir = "zip"
        if not os.path.exists(zip_dir):
            os.makedirs(zip_dir)
        
        # 保存文件
        file_path = os.path.join(zip_dir, file.filename)
        with open(file_path, "wb") as buffer:
            content = await file.read()
            buffer.write(content)
        
        return DocumentResponse(
            status="success",
            message=f"文件 {file.filename} 上传成功",
            data={
                "filename": file.filename,
                "file_path": file_path,
                "file_size": len(content)
            }
        )
    
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"文件上传失败: {str(e)}")

@router.get("/documents/test")
async def test_documents_api():
    """测试文档管理API"""
    return {
        "message": "文档管理API正常运行",
        "endpoints": [
            "GET /api/documents - 获取文档列表",
            "GET /api/documents/{doc_id} - 获取文档详情",
            "GET /api/documents/{doc_id}/files/{file_name} - 获取文件内容",
            "GET /api/documents/zip/status - 获取ZIP状态",
            "POST /api/documents/upload - 上传文档"
        ],
        "status": "healthy"
    }